#include "pagedevicemgmt.h"
#include "ui_pagedevicemgmt.h"
#include "pageusermgmt.h"
#include "ui_pageusermgmt.h"
#include <QMessageBox>
#include <QSqlError>
#include <QDebug>
#include <QComboBox>
#include <QFormLayout>
#include <QDialogButtonBox>
#include <QDateEdit>
#include <QLineEdit>
#include <QLayout>
#include <QPainter>

// 定义静态变量
QString pageDeviceMgmt::loginUsername = "";

// StatusDelegate 实现
StatusDelegate::StatusDelegate(QObject *parent)
    : QStyledItemDelegate(parent) {}

QWidget* StatusDelegate::createEditor(QWidget *parent,
                                      const QStyleOptionViewItem &/*option*/,
                                      const QModelIndex &/*index*/) const
{
    //qDebug() << "createEditor 被调用";
    QComboBox *comboBox = new QComboBox(parent);
    comboBox->addItems({"正常", "故障", "离线", "维护中"});
    return comboBox;
}

void StatusDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
    QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
    if (comboBox) {
        QString currentText = index.model()->data(index, Qt::EditRole).toString();
        if (currentText.isEmpty()) {
            comboBox->setCurrentText("正常");
        } else {
            comboBox->setCurrentText(currentText);
        }
    }
}

void StatusDelegate::setModelData(QWidget *editor,
                                  QAbstractItemModel *model,
                                  const QModelIndex &index) const
{
    //qDebug() << "setModelData 被调用";
    QComboBox *comboBox = qobject_cast<QComboBox*>(editor);
    if (comboBox) {
        model->setData(index, comboBox->currentText(), Qt::EditRole);
    }
}

void StatusDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    QStyleOptionComboBox comboBoxOption;
    comboBoxOption.rect = option.rect;
    comboBoxOption.state = option.state;
    comboBoxOption.currentText = index.model()->data(index, Qt::EditRole).toString();
    if (comboBoxOption.currentText.isEmpty()) {
        comboBoxOption.currentText = "正常";
    }
    comboBoxOption.frame = true;
    comboBoxOption.editable = false;

    QApplication::style()->drawComplexControl(QStyle::CC_ComboBox, &comboBoxOption, painter);
    QApplication::style()->drawControl(QStyle::CE_ComboBoxLabel, &comboBoxOption, painter);
}

// AddDeviceDialog 实现
pageDeviceMgmt::AddDeviceDialog::AddDeviceDialog(QWidget *parent)
    : QDialog(parent)
{
    QFormLayout *layout = new QFormLayout(this);

    nameEdit = new QLineEdit(this);
    typeEdit = new QLineEdit(this);
    locationEdit = new QLineEdit(this);
    manufacturerEdit = new QLineEdit(this);
    modelEdit = new QLineEdit(this);
    dateEdit = new QDateEdit(QDate::currentDate(), this);
    dateEdit->setCalendarPopup(true);

    layout->addRow("设备名称:", nameEdit);
    layout->addRow("设备类型:", typeEdit);
    layout->addRow("安装位置:", locationEdit);
    layout->addRow("制造商:", manufacturerEdit);
    layout->addRow("型号:", modelEdit);
    layout->addRow("安装日期:", dateEdit);

    QDialogButtonBox *buttonBox = new QDialogButtonBox(
                QDialogButtonBox::Ok | QDialogButtonBox::Cancel,
                this
                );
    connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
    connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);

    layout->addWidget(buttonBox);
    setLayout(layout);
    setWindowTitle("添加新设备");
}

// pageDeviceMgmt 主类实现
pageDeviceMgmt::pageDeviceMgmt(Mainbar *mainbar,QWidget *parent)
    : QWidget(parent),
      ui(new Ui::pageDeviceMgmt),
      m_deviceMgr(this),
      m_mainbar(mainbar)
{
    ui->setupUi(this);
    m_logManager = new LogManager(this);
    // 使用 DatabasePool 获取数据库连接
    QSqlDatabase db = DatabasePool::instance().getConnection();
    if (!db.isOpen()) {
        qDebug() << "无法打开数据库: " << db.lastError().text();
        return;
    }
    m_model = new QSqlTableModel(this, db);
    m_model->setTable("devices");
    m_model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    // 设置表头
    m_model->setHeaderData(0, Qt::Horizontal, tr("设备ID"));
    m_model->setHeaderData(1, Qt::Horizontal, tr("设备名称"));
    m_model->setHeaderData(2, Qt::Horizontal, tr("类型"));
    m_model->setHeaderData(3, Qt::Horizontal, tr("位置"));
    m_model->setHeaderData(4, Qt::Horizontal, tr("制造商"));
    m_model->setHeaderData(5, Qt::Horizontal, tr("型号"));
    m_model->setHeaderData(6, Qt::Horizontal, tr("状态"));
    m_model->setHeaderData(7, Qt::Horizontal, tr("安装日期"));

    if (!m_model->select()) {
        QMessageBox::critical(this, "错误", "无法加载设备数据: " + m_model->lastError().text());
    }

    // 配置代理模型
    m_proxyModel = new QSortFilterProxyModel(this);
    m_proxyModel->setSourceModel(m_model);
    m_proxyModel->setFilterKeyColumn(1); // 按设备名称搜索

    // 配置表格视图
    ui->tableView->setModel(m_proxyModel);
    StatusDelegate *statusDelegate = new StatusDelegate(this);
    ui->tableView->setItemDelegateForColumn(6, statusDelegate);
    if (ui->tableView->itemDelegateForColumn(6) == statusDelegate) {
        qDebug() << "StatusDelegate 设置成功";
    } else {
        qDebug() << "StatusDelegate 设置失败";
    }

    // 设置表格的编辑触发方式
    ui->tableView->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);

    // 连接信号槽
    connect(ui->lineEditSearch, &QLineEdit::textChanged, this, &pageDeviceMgmt::onSearch);
    connect(ui->btnDelete, &QPushButton::clicked, this, &pageDeviceMgmt::onDeleteDevice);
    connect(ui->btnSave, &QPushButton::clicked, this, &pageDeviceMgmt::onSaveChanges);
    connect(ui->btnRefresh, &QPushButton::clicked, this, &pageDeviceMgmt::refreshTable);
    connect(ui->btnAdd, &QPushButton::clicked, this, &pageDeviceMgmt::onAddDevice);
    connect(m_mainbar, &Mainbar::sendUsername, this, &pageDeviceMgmt::receiveUsername);

    // 创建居中委托实例
    CenteredItemDelegate *centeredDelegate = new CenteredItemDelegate(this);
    for (int col = 0; col < m_model->columnCount(); ++col) {
        if (col != 6) {
            ui->tableView->setItemDelegateForColumn(col, centeredDelegate);
        }
    }

    // 用户名列（第1列）设置只读委托
    ui->tableView->setItemDelegateForColumn(0, new ReadOnlyDelegate(this));
    ui->tableView->setItemDelegateForColumn(7, new ReadOnlyDelegate(this));

    // 自适应列宽
    ui->tableView->resizeColumnsToContents();
    // 手动加宽特定列（单位：像素）
    ui->tableView->setColumnWidth(6, 90);
    ui->tableView->setColumnWidth(7, 180);

    // 在构造函数中启用多选模式
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);


}

pageDeviceMgmt::~pageDeviceMgmt()
{
    delete ui;
}

void pageDeviceMgmt::receiveUsername(const QString &username)
{
    loginUsername = username;
    qDebug() << "pageDeviceMgmt收到用户名:" << loginUsername;
}


bool pageDeviceMgmt::executeTransaction(std::function<bool()> operation)
{
    QSqlDatabase db = m_model->database();
    db.transaction();
    if (operation()) {
        if (!db.commit()) {
            QMessageBox::critical(this, "错误", "提交失败: " + db.lastError().text());
            userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
            if (m_logManager) {
                m_logManager->recordSystemLog(
                            QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                            "OPERATION",
                            "ERROR",
                            QString("管理员[%1]提交数据库事务失败，错误信息: %2").arg(userInfo["username"].toString()).arg(db.lastError().text()),
                        userInfo["user_id"].toInt(),
                        -1
                        );
            }
            db.rollback();
            return false;
        }
        return true;
    } else {
        db.rollback();
        return false;
    }
}

void pageDeviceMgmt::onAddDevice()
{
    AddDeviceDialog dlg(this);
    if (dlg.exec() == QDialog::Accepted) {
        // 必填字段验证
        if (dlg.nameEdit->text().isEmpty() ||
                dlg.typeEdit->text().isEmpty() ||
                dlg.locationEdit->text().isEmpty())
        {
            QMessageBox::warning(this, "警告", "设备名称、类型和位置为必填项！");
            return;
        }

        // 调用设备管理类添加设备
        bool success = m_deviceMgr.addDevice(
                    dlg.nameEdit->text(),
                    dlg.typeEdit->text(),
                    dlg.locationEdit->text(),
                    dlg.manufacturerEdit->text(),
                    dlg.modelEdit->text(),
                    dlg.dateEdit->date().toString("yyyy-MM-dd")
                    );

        if (success) {
            refreshTable();
            QMessageBox::information(this, "成功", "设备添加成功");
            userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
            if (m_logManager) {
                m_logManager->recordSystemLog(
                            QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                            "OPERATION",
                            "INFO",
                            QString("管理员[%1]成功添加设备[%2]").arg(userInfo["username"].toString()).arg(dlg.nameEdit->text()),
                        userInfo["user_id"].toInt(),
                        -1
                        );
            }
        } else {
            QMessageBox::critical(this, "错误", "添加失败: 数据库操作错误");
            userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
            if (m_logManager) {
                m_logManager->recordSystemLog(
                            QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                            "OPERATION",
                            "ERROR",
                            QString("管理员[%1]添加设备[%2]失败，错误信息: %3").arg(userInfo["username"].toString()).arg(dlg.nameEdit->text()).arg(m_deviceMgr.getLastError()),
                        userInfo["user_id"].toInt(),
                        -1
                        );
            }
        }
    }
}

void pageDeviceMgmt::onDeleteDevice()
{
    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的设备！");
        return;
    }

    bool success = executeTransaction([this, selected]() {
        bool hasError = false;
        foreach (const QModelIndex &proxyIndex, selected) {
            QModelIndex sourceIndex = m_proxyModel->mapToSource(proxyIndex);
            int deviceId = m_model->data(sourceIndex.siblingAtColumn(0)).toInt();

            if (!m_deviceMgr.deleteDevice(deviceId)) {
                hasError = true;
                QMessageBox::critical(this, "错误", "删除失败: " + m_deviceMgr.getLastError());
                userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
                if (m_logManager) {
                    m_logManager->recordSystemLog(
                                QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                                "OPERATION",
                                "ERROR",
                                QString("管理员[%1]删除设备失败，错误信息: %2").arg(userInfo["username"].toString()).arg(m_model->lastError().text()),
                            userInfo["user_id"].toInt(),
                            deviceId
                            );
                }
                break;
            }
        }
        return!hasError;
    });
    if (success) {
        refreshTable();
        QMessageBox::information(this, "成功",
                                 QString("已删除 %1 台设备").arg(selected.size()));
        userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
        if (m_logManager) {
            m_logManager->recordSystemLog(
                        QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                        "OPERATION",
                        "INFO",
                        QString("管理员[%1]成功删除 %2 台设备").arg(userInfo["username"].toString()).arg(selected.size()),
                    userInfo["user_id"].toInt(),
                    -1
                    );
        }
    }
}

void pageDeviceMgmt::onSaveChanges()
{
    bool success = executeTransaction([this]() {
        if (m_model->submitAll()) {
            return true;
        } else {
            QMessageBox::critical(this, "错误", "保存失败: " + m_model->lastError().text());
            userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
            if (m_logManager) {
                m_logManager->recordSystemLog(
                            QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                            "OPERATION",
                            "ERROR",
                            QString("管理员[%1]修改设备信息失败，错误信息: %2").arg(userInfo["username"].toString()).arg(m_model->lastError().text()),
                        userInfo["user_id"].toInt(),
                        -1
                        );
            }
            return false;
        }
    });
    if (success) {
        QMessageBox::information(this, "成功", "修改已保存");
        userInfo = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
        if (m_logManager) {
            m_logManager->recordSystemLog(
                        QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                        "OPERATION",
                        "INFO",
                        QString("管理员[%1]修改设备信息成功!").arg(userInfo["username"].toString()),
                    userInfo["user_id"].toInt(),
                    -1
                    );
        }
    }
}


//刷新功能
void pageDeviceMgmt::refreshTable()
{
    m_model->select();
    m_proxyModel->invalidate();
    ui->tableView->resizeColumnsToContents();
    ui->tableView->setColumnWidth(6, 90);
    ui->tableView->setColumnWidth(7, 180);
}

//搜索功能
void pageDeviceMgmt::onSearch(const QString &text)
{
    m_proxyModel->setFilterFixedString(text);
}
